import React, { Component } from 'react'

import { formatMessage } from 'umi-plugin-locale';
import styles from '../index.less'
import { connect } from 'dva';
import { Scrollbars } from 'react-custom-scrollbars';
import BizIcon from '@/components/BizIcon'
import { Checkbox, Tree, Input, Tabs } from 'antd'

const { Search } = Input;

const getParentKey = (key, tree) => {
    let parentKey;
    for (let i = 0; i < tree.length; i++) {
        const node = tree[i];
        if (node.children) {
            if (node.children.some(item => item.key === key)) {
                parentKey = node.key;
            } else if (getParentKey(key, node.children)) {
                parentKey = getParentKey(key, node.children);
            }
        }
    }
    return parentKey;
};

@connect(({ unit, group: { groupTree }, loading }) => ({
    unit,
    groupTree,
    loading: loading.models.unit,
}))
class UnitTree extends Component {

    constructor(props) {
        super(props)
        this.unitAndUser = []
    }


    static defaultProps = {
        canDisabled: true,
    }


    state = {
        checkedNodes: [],
        expanded: false,
        expandedKeys: [],
        searchValue: '',
        autoExpandParent: true,
        defaultExpandedKeys: [],
        isOnline: 0,
        formatUnitAndUser: [],
    }


    timer = null

    componentDidMount() {
        this.getData()
        this.loopGetData()

    }

    componentWillUnmount() {
        this.timer && clearInterval(this.timer);
        this.setState = (state, callback) => {
            return
        }
    }

    fetchUnitAndUser(params) {
        this.props.dispatch({
            type: 'unit/fetchUnitAndUser',
            payload: params,
            callback: res => {
                let list = this.props.unit.formatUnitAndUserList
                this.setState({
                    formatUnitAndUser: list
                })
                this.unitAndUser = this.props.unit.unitAndUserList
                if (this.state.expanded === false) {
                    if (list) {
                        this.setState({
                            expandedKeys: [list[0].key],
                            expanded: true
                        })
                    }
                }
                
                // this.props.onFresh && this.props.onFresh(list)
            }
        })
    }

    

    onlyOnline(e) {
        e.target.checked === true ? this.getData(1) : this.getData(0)
    }

    getData(isOnline) {
        let payload = isOnline === 1 ? { isOnline: isOnline } : {}
        this.fetchUnitAndUser(payload)
        this.setState({ isOnline })
    }

    loopGetData() {
        this.timer && clearInterval(this.timer);
        this.timer = setInterval(() => this.getData(this.state.isOnline), 5000)
    }


    onExpand = expandedKeys => {
        this.setState({
            expandedKeys,
            autoExpandParent: false,
        });
    }
    onSelect = (selectedKeys, e) => {
        if (this.props.onSelect) {
            const key = e.node.key
            let item = this.checkNode(key)
            if (item) {
                this.props.onSelect(item)
            }
        }
    }
    doubleClick = (e, node) => {
        const key = node.key

        let item = this.checkNode(key)
        if (item) {
            this.props.onDoubleClick(key, item)
        }
    }
    onCheck = (_, e) => {
        let checkedNodes = e.checkedNodes.filter(item => {
            return item.type != 0
        })
        this.setState({
            checkedNodes: checkedNodes
        })
        // 当前选中的节点和选中状态
        let current = { ...e.node, checked: e.checked }
        this.props.onCheck(checkedNodes, current)
    }

    rightClick = (e) => {
        if (this.props.onRightClick) {
            this.props.onRightClick(e.node)
        }
    }

    checkNode(key) {
        for (let item of this.unitAndUser) {
            if (item.type === 1 && item.key === key) {
                return item;
            }
        }
        return false;
    }

    // updateTreeNode(key) {
    //     const loop = data => {
    //         data.map((item, index) => {
    //             if (item.key === key) {
    //                 if (!data[index].isPlay) {
    //                     data[index].title = data[index].title + ' 播放';
    //                     data[index].isPlay = true;
    //                     console.log('bofang')
    //                 } else {
    //                     data[index].isPlay = false;
    //                     data[index].title = data[index].title.replace('播放', '')
    //                     console.log('bu bofang')
    //                 }
    //                 return;
    //             }
    //             if (item.children) {
    //                 loop(item.children)
    //             }
    //         })
    //     }
    //     loop(this.state.formatUnitAndUser)
    // }

    onChange = e => {
        const { value } = e.target;
        const expandedKeys = this.unitAndUser
            .map(item => {
                if (item.title.indexOf(value) > -1) {
                    return getParentKey(item.key, this.state.formatUnitAndUser);
                }
                return null;
            })
            .filter((item, i, self) => item && self.indexOf(item) === i);
        this.setState({
            expandedKeys,
            searchValue: value,
            autoExpandParent: true,
        });
    };
    formatNumber = num => {
        return num < 10000 ? num : (num / 10000).toFixed(2) + '万';
    }

    loop = data => {
        const { searchValue } = this.state
        return data.map(item => {
            const index = item.title.indexOf(searchValue);
            const beforeStr = item.title.substr(0, index);
            const afterStr = item.title.substr(index + searchValue.length);
            let color = ''
            let fontWeight = ''
            let isOnline = true // 是否在线
            if (item.type === 1) {
                if (item.isOnline === 1 && item.isStreamOnline === 1) {
                    color = '#f30'
                    fontWeight = 'bold'
                } else if (item.isOnline === 1 && item.isStreamOnline === 0) {
                    color = '#f30'
                } else if (item.isOnline === 1 && item.isStreamOnline == -1) {
                    color = '#f90'
                } else {
                    color = '#bbb'
                    isOnline = false
                }
            }
            const title =
                index > -1 ? (
                    <span style={{ color, fontWeight }}>
                        {
                            item.type === 1 && <BizIcon style={{ marginRight: '5px' }} type="icon-user" />
                        }
                        {beforeStr}
                        <span style={{ fontWeight: 'bold', color: '#05f' }}>{searchValue}</span>
                        {afterStr}
                        {
                            item.type === 1 && isOnline === true && item.isStreamOnline === 0 && <span style={{ color: '#bbb' }}>[28181离线]</span>
                        }
                        {
                            item.type === 0 && <span className={styles.treeOnlineCount}>{item.online}/{item.total}</span>
                        }
                        {item.isDisabled === 1 ? <span style={{ paddingLeft: 5, color: '#bbb' }}>[{formatMessage({ 'id': 'common.disabled' })}]</span> : ''}
                    </span>
                ) : (
                    <span style={{ color: item.type === 1 ? ((item.isOnline === 1 && item.isStreamOnline === 1) ? '#f50' : '#bbb') : '' }}>
                        {
                            item.type === 1 && <BizIcon style={{ marginRight: '5px' }} type="icon-user" />
                        }
                        {item.title}
                    </span>
                );
            if (item.children) {
                let ret = { title, key: item.key, type: item.type, children: this.loop(item.children) };
                if (this.props.canDisabled === true) {
                    if (item.type === 1) {
                        ret.disabled = item.isOnline === 1 ? false : true
                    }
                }
                return ret
            }
            return {
                title,
                key: item.key,
                type: item.type
            };
        });
    }

    render() {

        const { expandedKeys, autoExpandParent } = this.state;
        const { userCount } = this.props.unit
        const { onlineUser, totalUser } = userCount
        const onlineRate = (onlineUser / totalUser * 100).toFixed(2)


        return (
            <div className={styles.leftSider}>
                <div className={styles.onlineCount}>
                    <div>{formatMessage({ id: 'live.users' })}: <span className={styles.textBlue}>{this.formatNumber(totalUser)}</span></div>
                    <div>{formatMessage({ id: 'live.online' })}: <span className={styles.textRed}>{this.formatNumber(onlineUser)}</span></div>
                    <div>{formatMessage({ id: 'live.onlineRate' })}: <span className={styles.textRed}>{isNaN(onlineRate) ? 0 : onlineRate}%</span></div>
                </div>
                <div className={styles.orgList}>
                    <Search className={styles.item} allowClear={true} placeholder={formatMessage({ id: 'live.search_placeholder' })} onChange={this.onChange} />
                    <div className={`${styles.item} flex inline-item justify-content-between`}>
                        <div style={{ fontWeight: 'bold' }}>
                            {formatMessage({ id: 'live.organization' })}
                            {
                                // this.state.checkedNodes.length > 0 && <span style={{ color: '#1890ff', fontWeight: 'normal', paddingLeft: '5px' }}>({this.state.checkedNodes.length})</span>
                            }
                        </div>
                        <div>
                            <Checkbox onChange={this.onlyOnline.bind(this)}>{formatMessage({ id: 'live.only_online_user' })}</Checkbox>
                        </div>
                    </div>
                    <div className={styles.tree}>
                        <Scrollbars
                            autoHide
                            autoHideTimeout={1000}
                            autoHideDuration={200}
                            style={{ height: '100%' }}
                        >
                            <Tree
                                style={{ marginLeft: '5px' }}
                                checkable={this.props.checkable ? true : false}
                                onExpand={this.onExpand}
                                expandedKeys={expandedKeys}
                                autoExpandParent={autoExpandParent}
                                onSelect={this.onSelect.bind(this)}
                                onDoubleClick={this.doubleClick}
                                onRightClick={this.rightClick}
                                onCheck={this.onCheck}
                                // selectable={false}
                                blockNode
                                treeData={this.loop(this.state.formatUnitAndUser)}
                            >
                            </Tree>

                        </Scrollbars>
                    </div>
                </div>
            </div>
        )
    }
}
export default UnitTree